package com.ruoyi.vstac.controller;

import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.vstac.domain.FileInfo;
import com.ruoyi.vstac.domain.Video;
import com.ruoyi.vstac.service.DeadlineService;
import com.ruoyi.vstac.service.IFileService;
import com.ruoyi.vstac.service.IVideoService;
import org.apache.commons.io.FileUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.vstac.domain.Entry;
import com.ruoyi.vstac.service.IEntryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 作品信息Controller
 * 
 * @author kingner
 * @date 2024-07-08
 */
@RestController
@RequestMapping("/vstac/entry")
public class EntryController extends BaseController
{
    @Autowired
    private IEntryService entryService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IVideoService videoService;
    @Resource
    private DeadlineService deadlineService;


    /**
     * 查询作品信息列表
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:list')")
    @GetMapping("/list")
    public TableDataInfo list(Entry entry)
    {
        startPage();
        List<Entry> list = entryService.selectEntryList(entry);
        return getDataTable(list);
    }


    /**
     * 导出作品信息列表
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:export')")
    @Log(title = "作品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Entry entry)
    {
        List<Entry> list = entryService.selectEntryList(entry);
        ExcelUtil<Entry> util = new ExcelUtil<Entry>(Entry.class);
        util.exportExcel(response, list, "作品信息数据");
    }

    /**
     * 获取作品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();

        // 获取该作品的基础信息
        Entry entry = entryService.selectEntryByUserId(userId);
        if(entry == null){
            return ajax.put("msg", "您未上传任何作品");
        }
        ajax.put("entry", entry);

        // 获取该作品的文件信息
        FileInfo[] fileInfos = fileService.selectFileByEntryId(entry.getEntryId()).toArray(new FileInfo[0]);
        ajax.put("fileInfos", fileInfos);

        // 获取该作品的视频信息
        Video[] videos = videoService.selectVideosByEntryId(entry.getEntryId()).toArray(new Video[0]);
        ajax.put("videos", videos);

        return ajax;
    }

    /**
     * 新增作品
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:add')")
    @Log(title = "作品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestParam("files") MultipartFile[] files, Entry entry) {
        try {
            deadlineService.isUploadTime();
        }catch (Exception e) {
            return AjaxResult.error("Error: " + e.getMessage());
        }
        // 获取当前登录用户的给作品赋值uid
        Long uid = getLoginUser().getUserId();
        entry.setUserId(uid);
        entry.setCreateTime(DateUtils.getNowDate());
        // 新增作品并获取自增id
        int entryId = entryService.insertEntry(entry);
        try{
            // 新增作品所上传的文件
            for (MultipartFile file : files) {
                String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
                if("pdf".equals(fileSuffix)){
                    fileService.insertFile(file,entry.getEntryId());
                }else if("mp4".equals(fileSuffix)){
                    videoService.insertVideo(file,entry.getEntryId());
                }else {
                    // 若上传文件类型不在pdf和mp4中，抛出TypeNotPresentException
                    throw new TypeNotPresentException(fileSuffix, new Throwable("File type not supported!"));
                }
            }
        }catch (Exception e){
                return AjaxResult.error("Error: " + e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 修改作品信息
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:edit')")
    @Log(title = "作品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Entry entry)
    {
        //判断是否超过上传时间
        try {
            deadlineService.isUploadTime();
        }catch (Exception e) {
            return AjaxResult.error("Error: " + e.getMessage());
        }


        entryService.updateEntry(entry);
        return AjaxResult.success();
    }

    /**
     * 修改文件
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:edit')")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @PutMapping("/file")
    public AjaxResult editFile(@RequestParam("file") MultipartFile file,int fileId) throws IOException {
        // 判断是否超过上传时间
        try {
            deadlineService.isUploadTime();
        }catch (Exception e) {
            return AjaxResult.error("Error: " + e.getMessage());
        }
        fileService.updateFile(file,fileId);
        return AjaxResult.success();
    }

    /**
     * 修改视频
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:edit')")
    @Log(title = "视频信息", businessType = BusinessType.UPDATE)
    @PutMapping("/video")
    public AjaxResult editVideo( @RequestParam("video") MultipartFile file,int videoId) throws IOException {
        // 判断是否超过上传时间
        try {
            deadlineService.isUploadTime();
        }catch (Exception e) {
            return AjaxResult.error("Error: " + e.getMessage());
        }
        videoService.updateVideo(file,videoId);
        return AjaxResult.success();
    }


    /**
     * 删除作品信息
     */
    @PreAuthorize("@ss.hasPermi('vstac:entry:remove')")
    @Log(title = "作品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{entryIds}")
    public AjaxResult remove(@PathVariable int[] entryIds)
    {
        return toAjax(entryService.deleteEntryByEntryIds(entryIds));
    }
}
